package com.google.code.virtualhockey.vhx.server.servlet

import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}
import com.google.code.virtualhockey.vhx.server.service.UserService

/**
 * Start servlet that is responsible for generating the VHX host page dynamically.
 */
class VhxStartServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) { handleRequest( req, resp ) }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) { handleRequest( req, resp ) }

  protected def handleRequest( rq: HttpServletRequest, rp: HttpServletResponse ) {
    val dispatcher = getServletContext.getRequestDispatcher( "/WEB-INF/jsp/index.jsp" )

    checkLogin( rq )
    dispatcher.forward( rq, rp )
  }

  /**
   * Checks if a user is logged in and adds its name and the link towards login or logoff page to
   * the request as additional attributes.
   */
  protected def checkLogin( rq: HttpServletRequest ) {
    val user = UserService.getGaeUser
    rq.setAttribute( "logout_url", UserService.getLogoutUrl )
    rq.setAttribute( "login_url", UserService.getLoginUrl )
    rq.setAttribute( "is_admin", UserService.isAuthenticated && UserService.isAdmin )
    rq.setAttribute( "is_gae_prod", !VhxEnv.isDevelopmentServer )
    if ( user != None )
      rq.setAttribute( "user", user.get.getEmail )
    else
      rq.setAttribute( "user", null )
  }
}
